const IO=require("socket.io")
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.dev')
const { msgType} = require('../config/result')
const {unzip} =require('../utils/index')
const moment = require('moment');

let connUserList=[]
function createSocket(httpserver)
  {
    connUserList=[]
    const io=IO(httpserver)
    io.on("connection",function(socket){//headers{origin}, handshake{time,query,auth
      //console.log('connected:',socket.handshake.headers) 
      const cookie=socket.handshake.headers.cookie
      const conectedtime=socket.handshake.time
      if(cookie)
      {
        let usercokie=cookie.split(';')
        let token=''
        let AdminUser=''
        if(usercokie.length===0 || cookie.indexOf('Admin-Token')<0){
          console.log('非法Cookie:',cookie)
          return
        }
        usercokie.forEach(item => {
          
          if(item.indexOf('Admin-Token')>-1){
            token=item.split('=')[1]
          }

          if(item.indexOf('Admin-User')>-1){
            AdminUser=item.split('=')[1]
          }
          
        });
        if(token.trim()==='' || AdminUser.trim()==='')
        {
          console.log('非法Token:',token)
          //socket.off()
          return
        }
        AdminUser=decodeURIComponent(AdminUser)
        let userinfo =JSON.parse(AdminUser)  
        //console.log('adminUser:',userinfo)
        let exist=connUserList.filter(item=>item.id===userinfo.id)
        if(exist && exist.length>0)
        {
          exist[0].connid=socket.conn.id
          exist[0].conntime=conectedtime
        }else{
          connUserList.push({...userinfo,'conntime':conectedtime,connid:socket.conn.id})
        }
        //console.log(`有用户连接：`,exist)
        sendAll(io)
      }else{
        console.log('缺失Cookie:')
      }
      
      //重新连接
      socket.on("reconnect", () => {
        let currentuser=connUserList.filter(item=>item.id===userinfo.id).connid=socket.conn.id
        console.log(`用户 ${currentuser.realName} 重新连接成功:`)
        //sendAll(io);
        });
      // 当客户端关闭的时
      socket.on("disconnect", () => {
        let curinfo=connUserList.filter(item=>item.connid===socket.conn.id)

        connUserList=connUserList.filter(item=>item.connid!==socket.conn.id)

        if(curinfo && curinfo.length>0)
          //console.log(`用户 ${curinfo[0].realName} 断开连接:`)
          sendAll(io);
        });
      socket.on("teamdoc",(msg)=>{ //teamdoc 为 文档协同消息
        let curinfo=connUserList.filter(item=>item.connid===socket.conn.id)
        let data=unzip(msg)
        let curuserinfo={}
        if(curinfo && curinfo.length>0){
          curuserinfo=curinfo[0]
        }else{
          let id = Math.random().toString().split(".")[1].slice(0, 3); 
          let realName= "匿名_" + id;
          curuserinfo={id:id,realName:realName}
        }
        const recivemessage=JSON.parse(data)
        //console.log(recivemessage)
        socket.broadcast.emit('teamdoc', 
          callbackdata({userinfo:curuserinfo, data:data, type:recivemessage.t === "mv" ? 3 : 2}));//user,data,type
      })

      socket.on(msgType.chatList, (msg) => {
        // 就给前端返回列表
        socket.emit(msgType.chatList, connUserList);
      });

      // 当客户端发来群发
      socket.on(msgType.chatGroup, (msg) => {
        //console.log(msg)
        socket.broadcast.emit(msgType.chatGroup, chatData(msg.data, msg.user));
      });
      })
  }

module.exports=createSocket

function chatData(data, user) {
  return {
    data,
    user,
  };
}

function callbackdata(args)
{
  const{userinfo,data,type}=args
  //console.log(user) 
  let resdata=JSON.stringify({
    createTime:moment().format('YYYY-MM-DD HH:mm:ss'),//dayjs().format("YYYYMMHH mm:hh:ss"),
    data:data,
    id: userinfo.id,
    returnMessage:"success",
    status:0,
    type:type,
    username: userinfo.realName,
  });
  //console.log(resdata)
  const ret= JSON.stringify({
    isTrusted:true,
    data:resdata,
    returnValue:true,
    type:"message"
  });
  //console.log(ret) 
  return ret
}

// 发送列表
function sendAll(io) {
  // 获取到列表;
  // let arr = Array.from(io.sockets.sockets)
  //   .map((item) => item[1].user)
  //   .filter((item) => item);
  io.emit(msgType.chatList, connUserList);
}